package com.two.screen.water.balance.utils

import android.content.Context
import android.os.Environment
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.lang.Exception

object DbUtils {
    const val TAG = "DbUtils"

    /***
     * 数据库 导入
     * @param context
     * @param dbDir
     * @param dbName
     */
    fun importDB(context: Context, dbDir: String?, dbName: String) {
        try {
            val sd = File(Environment.getExternalStorageDirectory(), dbDir)
            if (!sd.exists()) {
                d("importDB  -- 1  " + sd.path)
                sd.mkdirs()
            }
            val data = Environment.getDataDirectory()
            if (sd.canWrite()) {
                val currentDBPath = ("//data//" + context.packageName
                        + "//databases//" + dbName)
                val backupDB = File(data, currentDBPath)
                val currentDB = File(sd, dbName)
                val src = FileInputStream(currentDB).channel
                val dst = FileOutputStream(backupDB).channel
                dst.transferFrom(src, 0, src.size())
                src.close()
                dst.close()
                d("restore " + backupDB.absolutePath + " current " + currentDB.absolutePath)
                //Toast.makeText(getApplicationContext(), "Import Successful!", Toast.LENGTH_SHORT).show();
            }
        } catch (e: Exception) {
            d("restore e " + e.message)
            //Toast.makeText(getApplicationContext(), "Import Failed!", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 数据库 备份
     * @param context
     * @param dbDir
     * @param dbName
     */
    fun exportDB(context: Context, dbDir: String?, dbName: String) {
        try {
            val sd = File(Environment.getExternalStorageDirectory(), dbDir)
            if (!sd.exists()) {
                sd.mkdirs()
                d("exportDB  -- 1  " + sd.path)
            }
            val data = Environment.getDataDirectory()
            if (sd.canWrite()) {
                val currentDBPath = ("//data//" + context.packageName + "//databases//" + dbName)
                val currentDB = File(data, currentDBPath)
                val backupDB = File(sd, dbName)
                val src = FileInputStream(currentDB).channel
                val dst = FileOutputStream(backupDB).channel
                dst.transferFrom(src, 0, src.size())
                src.close()
                dst.close()
                d("backup " + backupDB.absolutePath + " current " + currentDB.absolutePath)

                //Toast.makeText(getApplicationContext(), "Backup Successful!", Toast.LENGTH_SHORT).show();
            }
        } catch (e: Exception) {
            d("backup e " + e.message)
            //Toast.makeText(getApplicationContext(), "Backup Failed!", Toast.LENGTH_SHORT).show();
        }
    }

    fun d(msg: String) {
        CommUtils.println("$TAG->", msg)
    }
}